<template>
    <div class="goods-evaluate-container">
        <!-- 导航栏 -->
        <TmallNavBar>
            <template #left><i class="icon iconfont icon-zuojiantou"></i></template>
            <template #default>商品评价</template>
            <template #right>
                <i class="icon iconfont icon-shouye1" @click="$router.push({path: '/'})"></i>
            </template>
        </TmallNavBar>

        <!-- 排序、筛选 -->
        <div class="sort-filter-box">
            <van-dropdown-menu ref="menuRef" active-color="#27BA9B">

                <van-dropdown-item @change="changeFilter" @open="openFilter" v-model="filterValue" :options="filters"/>

                <van-dropdown-item @change="changeSort" v-model="sortValue" :options="sorts"/>

                <van-dropdown-item @open="openComplexFilter" title="筛选" ref="complexFilterRef">
                    <!-- 商品款式 -->
                    <div class="complex-filter-wrapper">
                        <div class="complex-filter-item" v-for="(item, index) in goodsOptionList" :key="index">
                            <div class="complex-filter-title">{{ item.name }}</div>
                            <div class="complex-filter-values">
                                <van-tag 
                                    class="complex-filter-value" 
                                    v-for="(value, index) in item.values" :key="index"
                                    @click="selectOption(item.name,value)"
                                    size="large"
                                    :color="!selectOptionTexts.includes(item.name+'：'+value) ? '#EDEDED' : '#27BA9B' "
                                    :text-color="!selectOptionTexts.includes(item.name+'：'+value) ? '#000' : '#FFFFFF'"
                                    type="primary">{{ value }}</van-tag>
                            </div>
                        </div>
                    </div>
                    <div class="complex-filter-btn-box">
                        <van-button class="btn" color="#bbb" type="primary" round @click="onReset">
                            重置
                        </van-button>

                        <van-button class="btn" color="#27BA9B" type="primary" round @click="onConfirm">
                            确认
                        </van-button>
                    </div>
                </van-dropdown-item>
            </van-dropdown-menu>
        </div>

        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list
                v-model:loading="loading"
                :finished="finished"
                :finished-text="params.page_size < total ? '我也是有底线的~' : ''"
                @load="onLoadMore"
            >
                <!-- 骨架屏区 -->
                <van-skeleton v-if="isShowSkeleton">
                    <template #template>
                        <div class="skeleton-evaluate-wrapper">
                            <div class="skeleton-evaluate-item" v-for="(item, index) in skeletonLength" :key="index">
                                
                                <div class="skeleton-evaluate-user">
                                    <van-skeleton-image style="border-radius: 50%;width: 60px;height: 60px;"/>
                                    <div class="skeleton-evaluate-username-wrapper">
                                        <van-skeleton-paragraph row-width="40%" style="height: 25px;margin-bottom: 5px;"/>
                                        <van-skeleton-paragraph row-width="60%" />
                                    </div>
                                </div>
                                <div class="skeleton-evaluate-content">
                                    <van-skeleton-paragraph/>
                                    <van-skeleton-paragraph style="height: 30px;margin-top: 5px;"/>
                                </div>

                                <div class="skeleton-evaluate-image">
                                    <van-skeleton-image />
                                    <van-skeleton-image />
                                    <van-skeleton-image />
                                </div>

                                <div class="skeleton-evaluate-reply">
                                    <van-skeleton-paragraph style="height: 25px;"/>
                                </div>

                                <div class="skeleton-evaluate-operate">
                                    <van-skeleton-paragraph class="skeleton-evaluate-operate-item" row-width="30%"/>
                                    <van-skeleton-paragraph class="skeleton-evaluate-operate-item" row-width="30%"/>
                                    <van-skeleton-paragraph class="skeleton-evaluate-operate-item" row-width="30%"/>
                                </div>

                            </div>
                        </div>
                    </template>
                </van-skeleton>
                <div v-else>
                    <!-- 评价内容区 -->
                    <div class="evaluate-content-wrapper" v-if="goodsEvaluateList.length > 0">
                        <!-- 评价明细区 -->
                        <div class="evaluate-item" v-for="(item, index) in goodsEvaluateList" :key="index">

                            <!-- 评价用户区 -->
                            <div class="evaluate-user">
                                <div class="evaluate-user-avatar">
                                    <van-image round width="35" :src="global.MINIO_FILE_DOMAIN + item.avatar_url"></van-image>
                                </div>
                                <div class="evaluate-username-wrapper">
                                    <div class="evaluate-username">{{ item.username ? item.username : '匿名买家'}}</div>
                                    <div class="evaluate-time">{{ item.create_time }}</div>
                                </div>
                            </div>
                            
                            <!-- 评价商品信息区 -->
                            <div class="evaluate-goods">{{ item.goods_sku_text }}</div>

                            <!-- 评价内容 -->
                            <div class="evaluate-content">{{ item.contents }}</div>

                            <!-- 评价图片 -->
                            <div class="evaluate-image-wrapper">
                                <div class="evaluate-image-item" v-for="(item, index) in item.image_url_items" :key="index" v-show="index < 3">
                                    <van-image fit="cover" width="110" height="110"  :src=" global.MINIO_FILE_DOMAIN + item" />
                                </div>
                            </div>

                            <!-- 商家回复 -->
                            <div class="evaluate-reply-wrapper">
                                <div class="evaluate-reply-title">商家回复</div>
                                <div class="evaluate-reply-content">感谢亲的支持!欢迎下次光临!</div>
                            </div>

                            <!-- 评价操作区 -->
                            <div class="evaluate-operate-wrapper">
                                <div class="evaluate-operate-content">
                                    <van-icon size="28" name="share-o" />
                                    <span class="evaluate-operate-content-text">分享</span>
                                </div>

                                <div class="evaluate-operate-content">
                                    <van-icon size="28" name="chat-o" />
                                    <span class="evaluate-operate-content-text">评论</span>
                                </div>

                                <div class="evaluate-operate-content">
                                    <van-icon size="28" name="success" />
                                    <span class="evaluate-operate-content-text">有用</span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 空数据 -->
                    <div class="blank" v-else>
                        <van-image :src="blankImage" class="image" />
                        <span class="text">没有找到商品评价哟</span>
                        <van-button class="button" to="/">去首页看看</van-button>
                    </div>
                </div>
            </van-list>
        </van-pull-refresh>


        <!-- 返回顶部组件 -->
        <van-back-top right="5vw" bottom="5vh" />
    </div>
</template>

<script setup>
import { reactive, ref, inject, onMounted } from 'vue';
import { reqGoodsCommentListAPI, reqGoodsCommentTotalAPI } from '@/apis/goodsComment';
import { reqGetGoodsOptionListAPI } from '@/apis/goods'
import blankImage from '@/assets/images/blank.png'
import { useRoute } from 'vue-router'
import { showToast } from 'vant';



// -------------------------- 定义全局变量开始 --------------------------
// 路由
const route = useRoute()

// 是否显示骨架屏
const isShowSkeleton = ref(false)

// 是否完成
const finished = ref(false)

// 请求参数
const params = reactive({
    goods_id: route.query.goods_id,
    goods_sku_id: 0,
    goods_sku_text: '',
    is_append: 'all',
    label_id: 0,
    is_image: 'all',
    composite_score: 0,
    sort_field: 'id',
    sort_type: 'desc',
    page: 1,
    page_size: 10
})

// 骨架屏长度
const skeletonLength = ref(20)

// 加载中
const loading = ref(false)

// 定义商品评价列表
const goodsEvaluateList = ref([])

// 商品评价数量
const total = ref(0)

// 刷新中
const refreshing = ref(false)

// 是否挂载
const isMounted = ref(false)

// 全局属性
const global = inject('global')

// -------------------------- 定义全局变量结束 --------------------------




onMounted( async () => {
    isMounted.value = true
})


// ------------------------ 商品评价筛选功能开始 -------------------------
// 筛选值
const filterValue = ref(0)

// 筛选条件
const filters = ref([
    { text: '全部', value: 0 },
    { text: '视频/图片(0)', value: 1 },
    { text: '追评(0)', value: 2 },
    { text: '好评(0)', value: 3 },
])

const changeFilter = async (value) => {
    // 重置商品列表参数
    params.goods_sku_id = 0
    params.is_append = 'all'
    params.label_id = 0
    params.is_image = 'all'
    params.composite_score = 0

	// params.sort_field = 'id'
	// params.sort_mode = 'desc'
	params.page = 1
	goodsEvaluateList.value = []
    
    if (value == 1) { // 视频/图片
        params.is_image = '1'
    } else if (value == 2) { // 追评
        params.is_append = '1'
    } else if (value == 3) { // 好评
        params.composite_score = 5
    }

    finished.value = false

    isShowSkeleton.value = true
	await getGoodsEvaluateList()

    // 置顶
    window.scrollTo(0,0)

    isShowSkeleton.value = false
}

const isRequest = ref(false)
const openFilter = async () => {
    if (!isRequest.value) {
        await Promise.all([
            // 获取有图片的评价数量
            getGoodsEvaluateTotal({goods_id: route.query.goods_id, is_image: '1', mode: 'image'}),
            // 获取有追加的评价数量
            getGoodsEvaluateTotal({goods_id: route.query.goods_id, is_append: '1', mode: 'append'}),
            // 获取好评数量
            getGoodsEvaluateTotal({goods_id: route.query.goods_id, composite_score: 5, mode: 'praise'})
        ])
    }

    isRequest.value = true
}
// ------------------------ 商品评价筛选功能结束 -------------------------




// ------------------------ 商品评价排序功能开始 -------------------------
// 排序值
const sortValue = ref(0)

// 排序条件
const sorts = ref([
    { text: '默认排序', value: 0 },
    { text: '评分高到低', value: 1 },
    { text: '评分低到高', value: 2 },
])

const changeSort = async (value) => {
    if (value == 1) { // 评分高到低
        params.sort_field = 'composite_score'
        params.sort_type = 'desc'
    } else if (value == 2) { // 评分低到高
        params.sort_field = 'composite_score'
        params.sort_type = 'asc'
    } else {
        params.sort_field = 'id'
	    params.sort_type = 'desc'
    }

    params.page = 1
	goodsEvaluateList.value = []

    finished.value = false

    isShowSkeleton.value = true
	await getGoodsEvaluateList()

    // 置顶
    window.scrollTo(0,0)

    isShowSkeleton.value = false
}
// ------------------------ 商品评价排序功能结束 -------------------------




// --------------------- 获取商品列表功能开始 ---------------------
const getGoodsEvaluateList = async () => {
	if (finished.value == true) {
		return
	}

	loading.value = true

	// 请求数据
	const result = await reqGoodsCommentListAPI(params)
	let goodsComments = result.data.goods_comments != null ? result.data.goods_comments : []
	goodsEvaluateList.value.push(...goodsComments)
    total.value = result.data.total
	if (params.page < result.data.page_total) {
		params.page++
	} else {
		finished.value = true
	}

	loading.value = false
    refreshing.value = false
}

// 获取评价数量
const getGoodsEvaluateTotal = async (queryParam) => {
    // 请求数据
	const result = await reqGoodsCommentTotalAPI(queryParam)
    if (queryParam.mode == 'image') {
        filters.value[1].text = '视频/图片('+ result.data.total +')'
    } else if (queryParam.mode == 'append') {
        filters.value[2].text = '追评('+ result.data.total +')'
    } else if (queryParam.mode == 'praise') {
        filters.value[3].text = '好评('+ result.data.total +')'
    }
}
// --------------------- 获取商品列表功能结束 ---------------------








// -----------------------下拉刷新功能开始 ------------------------
const onRefresh = async () => {

    refreshing.value = true
    finished.value = false
    isShowSkeleton.value = true

	params.page = 1
    goodsEvaluateList.value = []

    await getGoodsEvaluateList()
    isShowSkeleton.value = false
}
// -----------------------下拉刷新功能结束 -----------------------




// ---------------------- 加载更多功能开始 ----------------------
const onLoadMore = async () => {
    // 当挂载时显示骨架屏
    if (isMounted.value) {
        isShowSkeleton.value = true
    }
	await getGoodsEvaluateList()
    isMounted.value = false
    isShowSkeleton.value = false
}
// ---------------------- 加载更多功能结束 ----------------------




// ---------------------- 商品款式功能开始 ----------------------
const goodsOptionList = ref([])
// 打开菜单栏时获取商品选项数据
const openComplexFilter = async () => {
    goodsOptionList.value = []
    const result = await reqGetGoodsOptionListAPI({goods_id: route.query.goods_id})
    const goodsOptionItems = result.data.goods_option_items != null ? result.data.goods_option_items : []
    goodsOptionItems.forEach(item => {
        item.values = item.value.split(',')
        goodsOptionList.value.push(item)
    });
}

const selectOptionTexts = ref([])
const selectOption = (name, value) => {
    const selectOptionText = name+'：'+value
    // 点击同一个选项值的索引
    const selfIndex = selectOptionTexts.value.findIndex((item) => item == selectOptionText)
    console.log('selfIndex =', selfIndex);

    let adjacentIndex = -1
    if (selfIndex == -1) {
        // 点击相邻的选项值索引 比如：尺码：35 尺码：36
        adjacentIndex = selectOptionTexts.value.findIndex((item) => {
            return item.split('：')[0] == name
        })
    }
    console.log('adjacentIndex =', adjacentIndex);
    if (selfIndex != -1) { // 取消同一个
        selectOptionTexts.value.splice(selfIndex, 1)
    } else {
        if(adjacentIndex != -1) {
            selectOptionTexts.value.splice(adjacentIndex, 1)
        }

        selectOptionTexts.value.push(selectOptionText)
    }
}


const complexFilterRef = ref()

// 确认
const onConfirm = async () => {
    // 判断选择商品款式
    if (selectOptionTexts.value.length > 0 && goodsOptionList.value.length != selectOptionTexts.value.length) {
        showToast('请选择完整的商品款式!')
        return false
    }

    complexFilterRef.value.toggle()
    finished.value = false

    // 重置商品列表参数
    params.page = 1
	goodsEvaluateList.value = []

    let goodsSkuText = []
    // 组装sku数据
    goodsOptionList.value.forEach(item => {
        selectOptionTexts.value.forEach(selectOptionText => {
            if (item.name == selectOptionText.split('：')[0]) {
                goodsSkuText.push(selectOptionText)
            }
        });
    })

    goodsSkuText = goodsSkuText.reverse()
    params.goods_sku_text = goodsSkuText.join(' ')

    isShowSkeleton.value = true
	await getGoodsEvaluateList()

    // 置顶
    window.scrollTo(0,0)
    
    isShowSkeleton.value = false
}

// 重置
const onReset = () => {
    selectOptionTexts.value = []
    params.goods_sku_text = ''
}
// ---------------------- 商品款式功能结束 ----------------------
</script>

<style lang="scss" scoped>

.skeleton-evaluate-wrapper {
    display: flex;
    flex-direction: column;
    margin-top: 100px;
    margin-bottom: 15px;
    width: 100%;
    .skeleton-evaluate-item {
        margin: 15px 0px 0px 0px;
        background: white;
        padding: 10px;
        border-radius: 10px;
        .skeleton-evaluate-user {
            display: flex;
            align-items: center;
            width: 100%;
            // border-bottom: 1px solid gainsboro;
            .skeleton-evaluate-username-wrapper {
                flex: 1;
                margin-left: 10px;
            }
        }

        .skeleton-evaluate-content {
            margin-top: 10px;
        }

        .skeleton-evaluate-image {
            display: flex;
            justify-content: space-between;
            margin-top: 10px;
        }
        .skeleton-evaluate-reply {
            margin-top: 10px;
        }

        .skeleton-evaluate-operate {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            margin-top: 10px;
            .skeleton-evaluate-operate-item {
                height: 30px;
            }
        }
    }
}
.goods-evaluate-container {
    // 排序、筛选盒子
    .sort-filter-box {
        margin-top: 45px;
        position:fixed;
        width: 100%;
        z-index: 100;
        .complex-filter-wrapper {
            display: flex;
            flex-direction: column;
            padding: 10px;
            .complex-filter-item {
                display: flex;
                flex-direction: column;
                margin-bottom: 10px;
                .complex-filter-title {
                    font-weight: bold;
                    font-size: 18px;
                }
                .complex-filter-values {
                    margin-top: 10px;
                    .complex-filter-value {
                        margin: 10px 15px;
                    }
                }
            }
        }
        .complex-filter-price-box {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .complex-filter-btn-box {
            display: flex;
            justify-content: space-between;
            padding: 15px 25px;
            .btn {
                height: 30px;
                width: 150px;
            }
        }
    }

    // 评价内容
    .evaluate-content-wrapper {
        display: flex;
        flex-direction: column;
        margin-top: 100px;
        margin-bottom: 15px;
        // 评价明细
        .evaluate-item {
            margin: 15px 10px 0px 10px;
            background: white;
            padding: 10px;
            border-radius: 10px;
            // 评价用户
            .evaluate-user {
                display: flex;
                align-items: center;
                border-bottom: 1px solid gainsboro;

                .evaluate-username-wrapper {
                    margin-left: 10px;

                    .evaluate-username {
                        font-size: 14px;
                        font-weight: bold;
                    }
                    .evaluate-time{
                        margin-top: 5px;
                        font-size: 13px;
                        color: #ccc;
                    }
                }
            }

            .evaluate-goods {
                margin-top: 10px;
                font-size: 14px;
                color: #ccc;

                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;

            }

            // 评价内容
            .evaluate-content {
                margin-top: 10px;
                margin-bottom: 10px;
                font-size: 16px;
                font-weight: 500;
                line-height: 20px;
                font-family:"Microsoft YaHei",Arial,Helvetica,sans-serif;
            }

            // 评价图片包裹
            .evaluate-image-wrapper {
                display: flex;
                flex-wrap: wrap;
                margin-top: 15px;
                .evaluate-image-item {
                    width: 30%;
                    height: 110px;
                    box-shadow: 1px 1px 5px #888888;
                }
                .evaluate-image-item:nth-child(2) {
                    margin: 0px 16px;
                }
            }

            // 商家回复区
            .evaluate-reply-wrapper {
                display: flex;
                margin-top: 15px;
                .evaluate-reply-title {
                    font-size: 16px;
                    font-weight: bold;
                }
                .evaluate-reply-content {
                    margin-left: 5px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }
            }

            // 操作区
            .evaluate-operate-wrapper {
                display: flex;
                margin-top: 15px;
                justify-content: space-between;
                .evaluate-operate-content {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    .evaluate-operate-content-text {
                        margin-left: 5px;
                        font-size: 18px;
                    }
                }
            }
        }
    }

    // 空状态
    .blank {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        height: 100vh;
        .image {
            width: 200px;
            height: 141px;
        }
        .text {
            color: #444;
            font-size: 13px;
            margin: 10px 0;
        }
        .button {
            width: 120px !important;
            height: 30px;
            line-height: 30px;
            margin-top: 10px;
            font-size: 13px;
            border-radius: 30px;
            color: #fff;
            background-color: #27ba9b;
        }
    }
}
</style>